package com.example.yrdev.ordering_system.Report;

import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.yrdev.ordering_system.Dialog.DateRangePickerDialog;
import com.example.yrdev.ordering_system.Fragment.PurchaseDetailFragment;
import com.example.yrdev.ordering_system.Common.CommonActivity;

import com.example.yrdev.ordering_system.Fragment.PurchaseOverallFragment;
import com.example.yrdev.ordering_system.Model.CustomViewHolder;
import com.example.yrdev.ordering_system.Model.Operator;
import com.example.yrdev.ordering_system.Model.PurchaseReport;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.http.HttpClient;
import com.example.yrdev.ordering_system.http.HttpResponseHandler;
import com.example.yrdev.ordering_system.http.NetWorkConstant;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 10/12/16.
 */

public class PurchaseCommodityActivity extends CommonActivity {

    @InjectView(R.id.line)LinearLayout line;

    @InjectView(R.id.content_container) FrameLayout content_container;

    ArrayList<PurchaseReport>arrayList;
    Integer paymode=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

   public PurchaseDetailFragment detailReportFragment;
   public PurchaseOverallFragment overallReportFragment;
    private boolean initButton=false;//初始化赛选按钮
  private  DateRangePickerDialog dateRangePickerDialog;
    int currentMode=0;//0：全部，1：明细

    @Override
    public void initView() {
        super.initView();

        setContentView(R.layout.purchase_commodity_layout);
        setBarTitle(GlobalFunction.getResourceString(this,R.string.purchase_detail));
        showBackButton();

        ButterKnife.inject(this);



        overallReportFragment=new PurchaseOverallFragment();
        overallReportFragment.setContext(this);

        detailReportFragment=new PurchaseDetailFragment();
        detailReportFragment.setCallback(new PurchaseDetailFragment.Callback() {
            @Override
            public void selectDate() {

                showDateSelection();

            }
        });
        detailReportFragment.setContext(this);

        RadioGroup radioGroup=(RadioGroup)findViewById(R.id.reportType);


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                RadioButton selectedRadioButton=(RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
                resetRadioButtonInGroup(radioGroup,false);
                selectedRadioButton.setBackgroundColor(Color.parseColor("#FF1B469A"));
                selectedRadioButton.setTextColor(Color.parseColor("#FFFFFF"));





                if (i == R.id.all) {
                    currentMode=0;


                    getFragmentManager().beginTransaction().replace(R.id.content_container,overallReportFragment).commit();

                } else {

                   showDateSelection();
                    currentMode=1;




                       getFragmentManager().beginTransaction().replace(R.id.content_container,detailReportFragment).commit();

                    // memberInfo.setVisibility(View.INVISIBLE);
                }


                initializeListData();

                // Calendar calendar=Calendar.getInstance();
            }
        });

        getFragmentManager().beginTransaction().add(R.id.content_container,overallReportFragment).commit();






        final RadioGroup radioGroup2=(RadioGroup)findViewById(R.id.payMode);

        radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {


                RadioButton radioButton=(RadioButton)findViewById(radioGroup2.getCheckedRadioButtonId());

                moveLineToCenter(line,radioButton);

                resetRadioButtonInGroup(radioGroup2,true);

                radioButton.setTextColor(Color.parseColor("#FF1B5EE5"));

                if (i==R.id.cash){
                    paymode=0;//现金

                }else {
                    paymode=3;//会员卡

                }


                initializeListData();


                //overallReportFragment.resetList();



                // Calendar calendar=Calendar.getInstance();

            }
        });

        initializeListData();


        showRightButtonWithListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
uploadReport();

            }
        },"上传");


    }

    private void uploadReport(){
        ArrayList <PurchaseReport> correspondReport=null;

        switch (currentMode){
            case 0:

        correspondReport=overallReportFragment.getCurrentReport();

                break;

            case 1:

            correspondReport=detailReportFragment.getCurrentReport();

                break;

        }


        GlobalFunction.printTextByTag(correspondReport.size()+"");
        if (correspondReport.size()>0){

            uploadCorrespondingReport(correspondReport);

        }else {

            GlobalFunction.ToastAlert(this,"没记录可上传");
        }



    }

    private void changeUploadMark(ArrayList <PurchaseReport> correspondReport){
        for (PurchaseReport report : correspondReport) {

          PurchaseReport.changeReportUploadMark(this,report);
        }
    }
    private void uploadCorrespondingReport(final ArrayList <PurchaseReport> correspondReport){

        ArrayList<HashMap>hashMapArrayList=new ArrayList<>();

        for (PurchaseReport report : correspondReport){

            if (report.getUploadMark()==0){

                HashMap<String,String> itemParam=new HashMap<>();
                itemParam.put("ticketID",report.getTicketID());
                itemParam.put("commodityID",report.getCommodityID());
                itemParam.put("volume",String.valueOf(report.getVolume()));
                itemParam.put("primeCost",report.getPrimeCost());
                itemParam.put("saleCost",report.getSaleCost());
                itemParam.put("cost",report.getCost());
                itemParam.put("restoredNum",String.valueOf(report.getRestoredNum()));
                itemParam.put("discount",report.getDisCount());
                itemParam.put("dateTime",report.getDateTimeCopy());
                itemParam.put("employeeID", Operator.getIntance().getEmployeeID());
                itemParam.put("vipCardID","");
                itemParam.put("payMode",paymode+"");
                hashMapArrayList.add(itemParam);

               // PurchaseReport.changeReportUploadMark(this,report);

            }

        }
        GlobalFunction.printTextByTag(hashMapArrayList+"");

        if (hashMapArrayList.size()>0){

            GlobalFunction.ToastAlert(this,"正在上传");

            HashMap<String,Object>body=new HashMap<>();
            body.put("num",String.valueOf(hashMapArrayList.size()));
            body.put("item",hashMapArrayList);

            HttpClient.postWithFunction(NetWorkConstant.HTTP_uploadPurchaseRecord,body,new HttpResponseHandler(){
                @Override
                protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                    super.handleSuccessMessage(statusCode, headers, responseBody);
                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(responseBody);
                        String resp=jsonObject.getString("response");

                        JSONObject respResponse=new JSONObject(resp);
                        String head=respResponse.getString("head");

                        JSONObject respHead=new JSONObject(head);
                        String respCode=respHead.getString("respCode");
                        GlobalFunction.printTextByTag(responseBody);
                        if (respCode.equals("0000")){

                            GlobalFunction.ToastAlert(PurchaseCommodityActivity.this,"上传成功");

                            changeUploadMark(correspondReport);

                            initializeListData();

                        }else {

                            GlobalFunction.ToastAlert(PurchaseCommodityActivity.this,"上传失败");
                        }

                    }catch (Exception e){


                    }










                }

                @Override
                protected void handleFailureMessage(Request request, IOException e) {
                    super.handleFailureMessage(request, e);
                }
            });


        }else {

            GlobalFunction.ToastAlert(this,"已把所有记录上传");

        }

    }


    private void showDateSelection(){

        if (dateRangePickerDialog==null)
          dateRangePickerDialog=new DateRangePickerDialog(PurchaseCommodityActivity.this);

        dateRangePickerDialog.setDateListener(new DateRangePickerDialog.DateListener() {
            @Override
            public void getDate(String startDate, String endDate) {

                detailReportFragment.checkDdateInterval(startDate,endDate);

            }
        });

        dateRangePickerDialog.show();


    }

    public  void initializeListData(){

        switch (currentMode){

            case 0:

                overallReportFragment.setPayModeType(paymode);

                break;

            case 1:

                detailReportFragment.setPayModeType(paymode);
                break;
        }




    }

    public void resetRadioButtonInGroup(RadioGroup radioGroup,Boolean payMode){

        for (int i=0;i<radioGroup.getChildCount();i++)
        {
            View view=radioGroup.getChildAt(i);

            if (view instanceof RadioButton){
                RadioButton radioButton=(RadioButton)radioGroup.getChildAt(i);

                if (payMode){


                    radioButton.setTextColor(Color.parseColor("#FFA5A6A8"));

                }else {

                 radioButton.setBackgroundColor(Color.parseColor("#b8d3ee"));
                radioButton.setTextColor(Color.parseColor("#c7c7c7"));
                }

            }

        }

    }
   private void moveLineToCenter(View line,View respView){

        float pos=respView.getX()+respView.getWidth()/2-line.getWidth()/2;

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        line.animate().translationX(pos);

    }




}
